package com.woniuxy.carlife.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.carlife.dto.CouponCategoryDto;
import com.woniuxy.carlife.domain.CouponCategory;
import com.woniuxy.carlife.mapper.CouponCategoryMapper;
import com.woniuxy.carlife.service.CouponCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author fx
 * @ClassName:CouponCategoryServiceImpl
 * @Description: 优惠券类别service实现类
 * @date 2021/4/6 20:00
 **/

@Service
public class CouponCategoryServiceImpl extends ServiceImpl<CouponCategoryMapper, CouponCategory> implements CouponCategoryService {

    @Resource
    private CouponCategoryMapper couponCategoryMapper;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 功能描述〈增加优惠券类别〉
     * @author:fx
     * @param: @param null:
     * @return:
     * @Date 2021/4/8 11:21
     * @throws
     */
    @Override
    public int saveCouponCategory(String couponCategory){
        //先根据名称查redis
        String s =(String) redisTemplate.opsForValue()
                .get("com.woniuxy:carlife:serviceproject:couponcagetory:name:" + couponCategory);
        if (ObjectUtils.isEmpty(s)){
            //根据名字查数据库
            CouponCategory coupon_category = couponCategoryMapper.selectOne(new QueryWrapper<CouponCategory>()
                    .eq("coupon_category", couponCategory));
            if (!ObjectUtils.isEmpty(coupon_category)){
                //如果数据库有数据就先把这个优惠券类别名存到redis
                redisTemplate.opsForValue()
                        .set("com.woniuxy:carlife:serviceproject:couponcagetory:name:" + couponCategory,
                                couponCategory);
                //设置过期时间,5分钟
                redisTemplate.expire("com.woniuxy:carlife:serviceproject:couponcagetory:name:" + couponCategory,
                        5*60,TimeUnit.SECONDS);
                return -1;
            }
        }else{
            return -1;
        }
        //创建类别对象
        CouponCategory category = new CouponCategory();
        //存储类别变量数据
        category.setCouponCategory(couponCategory);
        //1代表使用
        category.setCouponCategoryStatus(1);
        //存储新建时间
        category.setCouponCreateTime(new Timestamp(new Date().getTime()));
//        System.out.println(category);
        //执行存储操作
        int insert = couponCategoryMapper.insert(category);
        if (insert>0){
            return 1;
        }
        return 0;
    }

    /**
     * 功能描述〈查询所有优惠券类别〉
     * @author:fx
     * @param: @param null:
     * @return:
     * @Date 2021/4/8 11:24
     * @throws
     */
    @Override
    public List<CouponCategoryDto> findCouponCategory(){
        //先从redis中查询
        List<String> values = redisTemplate.opsForHash().values
                ("com.woniuxy:carlife:serviceproject:couponcategory");
        System.out.println(values);
        //判断从reids中获取的
        if (ObjectUtils.isEmpty(values)){
            //从数据库中查询
            List<CouponCategory> couponCategories = couponCategoryMapper.selectList(null);
            if (couponCategories.size()>0){
                //创建一个集合存储只有id和名称的自定义对象
                ArrayList<CouponCategoryDto> couponC = new ArrayList<>();
                //循环遍历所有类别集合
                for (CouponCategory c : couponCategories) {
//                    //声明一个dto类接收需要的变量
                    CouponCategoryDto couponCategoryDto = new CouponCategoryDto();
                    //把id和名称存到reidis中
                    couponCategoryDto.setCouponCategoryId(c.getCouponCategoryId());
                    System.out.println(c.getCouponCategory()+"=============");
                    couponCategoryDto.setName(c.getCouponCategory());
                    System.out.println(couponCategoryDto.getName()+"-----------");
                    //转换成json字符串
                    String s = JSON.toJSONString(c);
                    //存redis,只存id和名称（dto类）
                    redisTemplate.opsForHash()
                            .put("com.woniuxy:carlife:serviceproject:couponcategory",
                                    "id:"+c.getCouponCategoryId(),s);
                    //设置过期时间,5分钟
                    redisTemplate.expire("movie:name",5, TimeUnit.MINUTES);
//                    //把只有名称和id属性的对象添加到集合中
                    couponC.add(couponCategoryDto);
                }
                //把这个dto对象返回出去
                return couponC;
            }
        }else{
            ArrayList<CouponCategoryDto> couponCategories = new ArrayList<>();
            //对从redis中查询获得的map集合迭代
            for (int a=0;a<values.size();a++){
                //把json转换成自定义对象
                CouponCategoryDto category = JSON.parseObject
                        (values.get(a).toString(), CouponCategoryDto.class);
                //再把出来的对象放到集合中
                couponCategories.add(category);
            }
            //把这个dto对象返回出去
            return couponCategories;
        }
        return null;
    }

    /**
     * 功能描述〈根据类别id更改类别状态〉
     * @author:fx
     * @param: @param null:
     * @return:
     * @Date 2021/4/8 11:27
     * @throws
     */
    @Override
    public boolean updateCouponCategoryStatus(Integer id){
        //先从redis中查询这个对象
        String o = (String)redisTemplate.opsForHash()
                .get("com.woniuxy:carlife:serviceproject:couponcategory", "id:" + id);
        CouponCategory couponCategory=null;
        if (ObjectUtils.isEmpty(o)){
            //为空就从数据库中查询
            couponCategory = couponCategoryMapper.selectById(id);
            System.out.println("数据库查询");
        }else{
            couponCategory= JSON.parseObject(o, CouponCategory.class);
        }
        //判断当前状态
        if (couponCategory.getCouponCategoryStatus()==1){
            couponCategory.setCouponCategoryStatus(0);
        }else{
            couponCategory.setCouponCategoryStatus(0);
        }
        couponCategory.setCouponUpdateTime(new Timestamp(new Date().getTime()));
        int i = couponCategoryMapper.updateById(couponCategory);
        if (i>0){
            return true;
        }
        return false;
    }
}
